package com.mmall.service.impl;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CartMapper;
import com.mmall.dao.CartMapperCustom;
import com.mmall.dao.ProductMapper;
import com.mmall.dao.ProductMapperCustom;
import com.mmall.pojo.Cart;
import com.mmall.pojo.Product;
import com.mmall.service.ICartService;
import com.mmall.service.IFileService;
import com.mmall.util.BigDecimalUtil;
import com.mmall.util.PropertiesUtil;
import com.mmall.vo.CartProductVO;
import com.mmall.vo.CartVO;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Spliterator;

/**
 * @author cg.hu
 * @version 1.0.0
 * @date 2021-09-23 13:44
 * @description
 * @since 1.0.0
 */
@Service("iCartService")
public class CartServiceImpl implements ICartService {

    private static  final Logger logger = LoggerFactory.getLogger(CartServiceImpl.class);

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private CartMapperCustom cartMapperCustom;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductMapperCustom productMapperCustom;

    /**
     * @author cg.hu
     * @version 1.0.0
     * @date 2021-09-23 13:49
     * @description    商品添加购物车
     **/
    @Override
    public ServerResponse add(Integer userId, Integer count, Integer productId) {
        logger.info(">>>>>>>>>>>>>>> 商品添加购物车 <<<<<<<<<<<<<<<<<");
        Cart cart = cartMapperCustom.selectCartByUserIdProductId(userId, productId);
        int rowCount = 0;
        if (null == cart) {
            // 需要新增
            Cart cartItem = new Cart();
            cartItem.setQuantity(count);
            cartItem.setChecked(Const.Cart.CHECKED);
            cartItem.setProductId(productId);
            cartItem.setUserId(userId);
            rowCount = cartMapper.insert(cart);
            if (rowCount == 0) {
                logger.info(">>>>>>>>>>>>>>> 商品添加购物车失败 <<<<<<<<<<<<<<<<<");
                return ServerResponse.createByErrorMessage("商品添加购物车失败");
            }
        }

        if (null != cart) {
            // 商品在购物车中已经存在则将数量相加
            count = cart.getQuantity() + count;
            cart.setQuantity(count);
            rowCount = cartMapper.updateByPrimaryKeySelective(cart);
            if (rowCount == 0) {
                logger.info(">>>>>>>>>>>>>>> 商品添加购物车失败, 更新商品数量失败 <<<<<<<<<<<<<<<<<");
                return ServerResponse.createByErrorMessage("商品添加购物车失败");
            }
        }
        return this.list(userId);
    }

    /**
     * @author cg.hu
     * @version 1.0.0
     * @date 2021-09-27 13:48
     * @description    更新购物车信息
     **/
    @Override
    public ServerResponse update(Integer userId, Integer count, Integer productId) {
        logger.info(">>>>>>>>>>>>>>> 更新购物车信息 <<<<<<<<<<<<<<<<<");
        Cart cart = cartMapperCustom.selectCartByUserIdProductId(userId, productId);
        int rowCount = 0;
        if (null == cart) {
            return ServerResponse.createByErrorMessage("购物车数据不存在");
        }
        cart.setQuantity(count);
        cartMapper.updateByPrimaryKeySelective(cart);
        return this.list(userId);
    }

    private CartVO getCartVOLimit(Integer userId) {
        CartVO cartVO = new CartVO();
        List<Cart> cartList = cartMapperCustom.selectCartByUserId(userId);
        List<CartProductVO> cartProductVOList = Lists.newArrayList();
        BigDecimal cartTotalPrice = new BigDecimal("0");
        if (CollectionUtils.isNotEmpty(cartList)) {
            for (Cart cartItem : cartList) {
                CartProductVO cartProductVO = new CartProductVO();
                BeanUtils.copyProperties(cartItem, cartProductVO);

                Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
                if (null == product) {
                    logger.info("product is null");
                }
                BeanUtils.copyProperties(product, cartProductVO);
                // 判断库存
                int buyLimitCount = 0;
                if (product.getStock() >= cartItem.getQuantity()) {
                    // 库存充足的时候
                    buyLimitCount = cartItem.getQuantity();
                    cartProductVO.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                } else {
                    buyLimitCount = product.getStock();
                    cartProductVO.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL);
                    // 购物车中更新有效库存
                    Cart cartForQuantity = new Cart();
                    cartForQuantity.setId(cartItem.getId());
                    cartForQuantity.setQuantity(buyLimitCount);
                    cartMapper.updateByPrimaryKeySelective(cartForQuantity);
                }
                cartProductVO.setQuantity(buyLimitCount);
                // 计算总价
                cartProductVO.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(),
                        cartProductVO.getQuantity().doubleValue()));

                cartProductVO.setProductChecked(cartItem.getChecked());

                if (cartItem.getChecked() == Const.Cart.CHECKED) {
                    // 如果已经勾选，增加到整个的购物车总价中
                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVO.getProductTotalPrice().doubleValue());
                }

                cartProductVOList.add(cartProductVO);
            }
        }
        cartVO.setCartTotalPrice(cartTotalPrice);
        cartVO.setCartProductVoList(cartProductVOList);
        cartVO.setAllChecked(this.getAllCheckedStatus(userId));
        cartVO.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/"));
        return cartVO;
    }

    private boolean getAllCheckedStatus(Integer userId) {
        if (null == userId) {
            return false;
        }
        return cartMapperCustom.selectCartProductCheckedStatusByUserId(userId) == 0;
    }

    /**
     * @author cg.hu
     * @version 1.0.0
     * @date 2021-09-27 14:02
     * @description    购物车删除商品
     **/
    @Override
    public ServerResponse deleteProduct(Integer userId, String productIds) {
        List<String> productIdList = Splitter.on(",").splitToList(productIds);
        cartMapperCustom.deleteByUserIdProductIds(userId,productIdList);
        return this.list(userId);
    }

    /**
     * @author cg.hu 
     * @version 1.0.0   
     * @date 2021-09-27 14:40      
     * @description    购物车列表
     **/
    @Override
    public ServerResponse list(Integer userId) {
        CartVO cartVO = this.getCartVOLimit(userId);
        return ServerResponse.createBySuccess(cartVO);
    }

    /**
     * @author cg.hu
     * @version 1.0.0
     * @date 2021-09-28 9:11
     * @description    全选或反选
     **/
    @Override
    public ServerResponse selectOrUnSelect(Integer userId, Integer checked, Integer productId) {
        cartMapperCustom.checkedOrUncheckedProduct(userId, checked, null);
        return this.list(userId);
    }

    /**
     * @author cg.hu 
     * @version 1.0.0   
     * @date 2021-09-28 9:32
     * @description    
     **/
    @Override
    public ServerResponse getCartProductCount(Integer userId) {
        if (null == userId) {
            return ServerResponse.createBySuccess(0);
        }
        return ServerResponse.createBySuccess(cartMapperCustom.selectCartProductCount(userId));
    }
}
